<template>
  <div class="chat-list-container safe-area-bottom" v-ai-tip>
    <div class="chat-list">
      <message
        v-for="(item, index) in chatList"
        :key="index"
        :item="item"
        :index="index"
        :isSend="index % 2 == 0"
      />
      <followUp
        :suggestions="suggestions"
        :isLoading="isLoadingSuggestions"
        v-show="suggestions.length > 0 || isLoadingSuggestions"
        @onSelectSuggestion="onSelectSuggestion"
      />
      <loading v-show="isLoadingSuggestions" />
    </div>
    <div class="bottom-view">
      <img src="../../icons/svg/commonCozeBot/menu_icon.svg" @click="onClickRecord" />
      <div class="input-box">
        <van-field
          :class="['input-field']"
          v-model="inputMsg"
          ref="inputField"
          placeholder="您可以问我任何问题"
          enterkeyhint="send"
          :border="false"
          @keydown.enter="handleSend"
          @focus="onFocus"
          @blur="onBlur"
        />
        <img
          src="../../icons/svg/commonCozeBot/send_icon.svg"
          v-show="isFocus"
          @click="handleSend"
        />
      </div>
    </div>

    <van-popup
      v-model:show="showLeftNavigation"
      position="left"
      round
      :style="{ height: '100%', width: '80%' }"
    >
      <leftNavigation
        @onClose="
          () => {
            showLeftNavigation = false;
          }
        "
      />
    </van-popup>
  </div>
</template>

<script setup>
import { onMounted, computed, ref, watch } from "vue";
import message from "./message/index.vue";
import loading from "./message/loading.vue";
import followUp from "./message/followUp.vue";
import { useCommonCozeBotStore } from "@/store";
import { useRoute } from "vue-router";
import leftNavigation from "./record/leftNavigation.vue";

const store = useCommonCozeBotStore();
const route = useRoute();

onMounted(() => {
  initData();
});

// { value: "", isSend: false}
const chatList = computed(() => {
  return store.chatList;
});

const isLoading = computed(() => {
  return store.isLoading;
});

const idTypeMap = computed(() => {
  return store.idTypeMap;
});

async function initData() {
  // bootId
  const { token, isTest, userId, botId } = route.query;
  if (isTest) {
    setToken(
      "Bearer2 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzaW1wbGVMb2dpbiI6dHJ1ZSwiaXNzIjoib2N0IiwibmFtZSI6IuacseW6huelpSIsImlkIjoiZjBmZTZmYmQtYzdkMS00NTllLWJkMDYtODczZDA1ZGY1OWZjIiwib3JnSWQiOiIyNDJiMjU1YS1hNWE4LTQ4MGMtYTI1MS0zOWNhZTAyMGVhNjAifQ.JIX-xDVThCQwGqKo_U-pRgMPqmIhkglxchCJf5o8B1I"
    );
  }
  if (token && token.length > 0) {
    setToken(token);
  }

  store.userId = userId;
  if (!store.userId) {
    const userInfoStr = localStorage.getItem("yxt-userInfo");
    const userInfo = JSON.parse(userInfoStr);
    if (userInfo) {
      store.userId = userInfo.id;
    }
  }
  if (botId) {
    store.botId = botId;
    // idTypeMap.value.map((item) => {
    //   if (item.id === botId) {
    //     const docTitle = item.title;
    //     setPageTitle(docTitle);
    //   }
    // });
  }
  store.addWelcomeMessage();
}

const inputMsg = ref("");
const inputField = ref(null);
const isFocus = ref(false);

function handleSend() {
  let msg = inputMsg.value.trim();
  if (msg.length == 0) {
    showToast("请先输入内容");
    return;
  }
  store.sendMessageToCozeAction(msg);
  inputMsg.value = "";
  inputField.value.blur();
  scrollBottom();
}

function onFocus() {
  isFocus.value = true;
}
function onBlur() {
  setTimeout(() => {
    isFocus.value = false;
  }, 200);
}

function scrollBottom() {
  setTimeout(() => {
    let element = document.getElementsByClassName("chat-list")[0];
    let lastChild = element.lastElementChild;
    lastChild.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
  }, 200);
}

const isLoadingSuggestions = computed(() => {
  return store.isLoadingSuggestions;
});

const showLeftNavigation = ref(false);
function onClickRecord() {
  showLeftNavigation.value = true;
}

// AI 建议问题
const suggestions = computed(() => {
  return store.suggestions;
});

function onSelectSuggestion(content) {
  store.sendMessageToCozeAction(content);
  scrollBottom();
}

// 流式回答内容
const tempAnswer = computed(() => store.tempAnswer);

watch(isLoading, (newValue, oldValue) => {
  if (newValue === false && oldValue === true) {
    scrollBottom();
  }
});
watch(tempAnswer, () => scrollBottom());
watch(suggestions, () => scrollBottom());
</script>

<style lang="less" scoped>
.chat-list-container {
  width: 100%;
  height: 100vh;
  background: #e6edfa;
  display: flex;
  flex-direction: column;
}

.chat-list {
  padding: 10px 20px;
  height: 100vh;
  flex: 1;
  overflow-y: auto;
}

.bottom-view {
  height: 50px;
  padding: 0 14px;
  padding-bottom: 36px;
  display: flex;
  flex-direction: row;
  align-items: center;

  img {
    width: 32px;
    height: 32px;
  }
}

.input-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex: 1;
  margin: 4px 4px 4px 4px;
  background-color: white;
  padding: 4px 8px;
  border-radius: 20px;

  .input-field {
    padding: 0;
    line-height: 26px;
    margin-bottom: 3px;
    margin-left: 4px;
    background-color: transparent;
  }
}

.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
